package com.example.web_playback

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.view.ViewGroup
import android.view.Gravity
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue

class MainActivity : AppCompatActivity() {
    
    private lateinit var webView: WebView
    private lateinit var downloadManager: ResourceDownloadManager
    private lateinit var homeButton: Button
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全屏模式
        setupFullscreen()
        
        setContentView(R.layout.activity_main)
        
        initializeViews()
        setupWebView()
        setupFloatingHomeButton()
    }
    
    private fun setupFullscreen() {
        // 隐藏状态栏和导航栏
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        )
        
        // 设置窗口标志
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        
        // 隐藏ActionBar
        supportActionBar?.hide()
    }
    
    private fun initializeViews() {
        webView = findViewById(R.id.webView)
        downloadManager = ResourceDownloadManager(this)
    }
    
    private fun setupWebView() {
        // 添加JavaScript接口
        webView.addJavascriptInterface(this, "AndroidInterface")
        
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                updateAllLinks()
            }
        }
        
        webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            loadWithOverviewMode = true
            useWideViewPort = true
            builtInZoomControls = false
            displayZoomControls = false
            // 隐藏缩放控件
            setSupportZoom(false)
            setBuiltInZoomControls(false)
            setDisplayZoomControls(false)
            // 允许访问外部存储文件
            allowFileAccess = true
            allowFileAccessFromFileURLs = true
            allowUniversalAccessFromFileURLs = true
            // 允许混合内容
            mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        
        // 根据屏幕方向调整WebView设置
        adjustWebViewForOrientation()
        
        // 加载本地HTML页面
        webView.loadUrl("file:///android_asset/index.html")
    }
    
    private fun adjustWebViewForOrientation() {
        val orientation = resources.configuration.orientation
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏时的特殊设置
            webView.settings.apply {
                loadWithOverviewMode = true
                useWideViewPort = true
            }
        } else {
            // 竖屏时的设置
            webView.settings.apply {
                loadWithOverviewMode = true
                useWideViewPort = true
            }
        }
    }
    
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        // 屏幕方向改变时重新调整WebView
        adjustWebViewForOrientation()
    }
    
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            // 重新应用全屏设置
            setupFullscreen()
        }
    }
    
    private fun updateAllLinks() {
        // 页面加载完成后，JavaScript会自动调用Android接口
        // 这里不需要额外的处理
    }
    
    // 供JavaScript调用的方法
    @android.webkit.JavascriptInterface
    fun getLocalResourcePath(originalPath: String): String {
        return downloadManager.getLocalResourcePath(originalPath)
    }
    
    private fun setupFloatingHomeButton() {
        // 创建悬浮按钮
        homeButton = Button(this)
        homeButton.text = "🏠"
        homeButton.textSize = 24f
        
        // 设置按钮样式
        val drawable = GradientDrawable()
        drawable.shape = GradientDrawable.OVAL
        drawable.setColor(Color.parseColor("#80000000")) // 半透明黑色背景
        drawable.setStroke(4, Color.WHITE) // 白色边框
        homeButton.background = drawable
        
        // 设置按钮大小
        val size = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 
            60f, 
            resources.displayMetrics
        ).toInt()
        
        val layoutParams = ViewGroup.LayoutParams(size, size)
        homeButton.layoutParams = layoutParams
        
        // 设置按钮位置（右下角）
        val margin = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 
            20f, 
            resources.displayMetrics
        ).toInt()
        
        // 创建布局参数
        val floatingParams = ViewGroup.MarginLayoutParams(size, size)
        floatingParams.setMargins(0, 0, margin, margin)
        
        // 添加到根布局
        val rootView = findViewById<ViewGroup>(android.R.id.content)
        rootView.addView(homeButton, floatingParams)
        
        // 延迟设置按钮位置，确保布局已完成
        homeButton.post {
            val screenWidth = resources.displayMetrics.widthPixels
            val screenHeight = resources.displayMetrics.heightPixels
            homeButton.x = (screenWidth - size - margin).toFloat()
            homeButton.y = (screenHeight - size - margin).toFloat()
            
            // 调试日志
            android.util.Log.d("FloatingButton", "按钮位置: x=${homeButton.x}, y=${homeButton.y}")
            android.util.Log.d("FloatingButton", "屏幕尺寸: ${screenWidth}x${screenHeight}")
            android.util.Log.d("FloatingButton", "按钮尺寸: ${size}x${size}")
        }
        
        // 设置点击事件
        homeButton.setOnClickListener {
            // 返回主页面
            webView.loadUrl("file:///android_asset/index.html")
        }
        
        // 设置按钮透明度动画效果
        homeButton.alpha = 0.9f
        homeButton.visibility = View.VISIBLE
        
        // 确保按钮在最前面
        homeButton.bringToFront()
        
        homeButton.setOnTouchListener { _, event ->
            when (event.action) {
                android.view.MotionEvent.ACTION_DOWN -> {
                    homeButton.alpha = 1.0f
                    homeButton.scaleX = 1.1f
                    homeButton.scaleY = 1.1f
                    android.util.Log.d("FloatingButton", "按钮被按下")
                }
                android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                    homeButton.alpha = 0.9f
                    homeButton.scaleX = 1.0f
                    homeButton.scaleY = 1.0f
                    android.util.Log.d("FloatingButton", "按钮被释放")
                }
            }
            false
        }
    }
    
    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}
